# -*- coding: utf-8 -*-
# Created by liangfuting on 2020/8/19
# Copyright (c) 2020 liangfuting. All rights reserved.


from django.shortcuts import render, redirect,reverse,HttpResponse
from django.urls import path
from django.utils.safestring import mark_safe

from stark.service.v1 import StarkHandler,get_manytomany,get_choice_text,BootStrapModelForm
from stark.forms.widgets import DateTimePickerInput
from django.db import transaction
from web.models import Customer,ConsultRecord,UserInfo
from django.conf import settings


class PublicCustomerModelForm(BootStrapModelForm):
    class Meta:
        model=Customer
        exclude=['consultant']
        # widgets={
        #     'date':DateTimePickerInput,
        #     'last_consult_date':DateTimePickerInput,
        # }


class PublicCustomerHandler(StarkHandler):
    def display_consult_record(self,obj=None,is_header=None):
        if is_header:
            return '查看跟进记录'
        target_url=self.reverse_consult_record_url(pk=obj.pk)
        return mark_safe("<a href='{}'>查看跟进记录</a>".format(target_url))


    list_display = ['name','qq',get_manytomany('课程','course'),display_consult_record,get_choice_text('状态','status')]
    model_form_class = PublicCustomerModelForm

    def get_query_set(self,request,*args,**kwargs):
        return self.model_class.objects.filter(consultant__isnull=True)

    def extra_urls(self):
        patterns = []
        patterns.append(path('consult/record/<int:pk>/', self.wapper(self.consult_record), name=self.get_consult_record_url_name))
        # stark/ web/userinfo/ reset/password/<int:pk>/ [name='web_userinfo_reset_pwd']

        return patterns

    def consult_record(self,request,pk):
        record_list=ConsultRecord.objects.filter(customer__id=pk).all()
        #通过面板展示跟进记录，页面不同于stark的页面
        # print(pk,record_list)
        customer_obj=self.model_class.objects.filter(pk=pk).first()
        return render(request,'web/record_view.html',{'record_list':record_list,'customer':customer_obj})

    def get_add_btn(self,request,*args,**kwargs):
        #子类可继承函数，预留此钩子函数
        #粒度控制到按纽,新思路
        from django.conf import settings
        permission_dict=request.session.get(settings.PERMISSION_SESSION_KEY)
        if self.get_add_url_name in permission_dict:

            return super().get_add_btn(request,*args,**kwargs)
        else:
            return None

    @property
    def get_consult_record_url_name(self):
        return self.get_url_name('record_view')

    def reverse_consult_record_url(self,*args,**kwargs):
        return self.reverse_common(self.get_consult_record_url_name, *args, **kwargs)

    def action_multi_apply(self,request,*args,**kwargs):
        """
        批量申请帐户到私人账户
        :param request:
        :param args:
        :param kwargs:
        :return:
        """

        pk_list=request.POST.getlist('pk')
        # print(pk_list)
        current_user=UserInfo.objects.filter(name=request.user)
        #私人账户的客户数量
        private_customer_count=Customer.objects.filter(consultant_id=11,status=2).count()
        # print(current_user_sum)
        # print(request.session['user_info']['id'])
        user_id=request.session['user_info']['id']


        # print(customers.count())
        # 准备转化的客户数量，两者之和不超过150个
        if private_customer_count+len(pk_list)>150:
            return HttpResponse('customer num exceed，您已经有{}个客户,最多只能申请{}个'.format(private_customer_count,150-private_customer_count))
        #解决同时提交冲突的问题
        #数据库中加锁解决，
        flag=False
        with transaction.atomic():
            customers = Customer.objects.filter(id__in=pk_list, status=2, consultant__isnull=True).select_for_update()
            if len(customers)==len(pk_list):
                #不能使用bulk_update
                # Customer.objects.bulk_update(customers)
                customers.update(consultant=user_id)
                # current_user.customer_set(customers)
                flag=True

        if not flag:
            return HttpResponse('手速太慢了，选中的客户已被别我抢走了，请重新选择')
        return redirect(self.reverse_list_url())



    action_multi_apply.text='批量申请到私人帐户'
    # action_list = self.get_action_list()
    # print(action_list)

    def get_action_list(self):
        #需要起一个新的名字
        action_list=[]
        action_list.extend(super(PublicCustomerHandler,self).get_action_list())
        action_list.append(self.action_multi_apply)
        # print(action_list)
        return action_list



